﻿using System;
using System.Xml;
using System.Web;

namespace Landscape
{
    class DocumentTemplate : Template
    {
        public string LayoutName;

        public DocumentTemplate(string xmlTemplatePath) : base(xmlTemplatePath)
        {
            XmlNode rootTemplateNode = null;
            XmlNodeList xsltTemplates = TemplateDom.GetElementsByTagName("template", Renderer.xslNS);
            if (xsltTemplates.Count > 0)
            {
                foreach (XmlNode tplNode in xsltTemplates)
                {
                    XmlNode matchAttr = tplNode.Attributes.GetNamedItem("match");
                    XmlNode wrapperAttr = tplNode.Attributes.GetNamedItem("wrapper", Renderer.landscapeNS);

                    if (matchAttr != null && matchAttr.Value.Equals("/"))
                    {
                        rootTemplateNode = tplNode;
                        if (wrapperAttr != null && !string.IsNullOrEmpty(wrapperAttr.Value))
                        {
                            LayoutName = wrapperAttr.Value;

                            rootTemplateNode.Attributes.RemoveNamedItem("wrapper", Renderer.landscapeNS);
                            break;
                        }
                    }
                }
            }

            if (rootTemplateNode == null)
            {
                throw new Exception("Template does not contain a root template (<xsl:template match=\"/\"> ... </xsl:template>)");
            }

            if (string.IsNullOrEmpty(LayoutName))
            {
                Renderer.CreateXslOutput(TemplateDom, OutputMethod, Renderer.xmlDocTypePublic, Renderer.xmlDocTypeSystem, "utf-8", true, false, true, false);
            }
            else
            {
                OutputMethod = Renderer.OutputMethods.Xml;
                Renderer.CreateXslOutput(TemplateDom, OutputMethod, null, null, "utf-8", true, false, true, false);
            }

            // create compiled transform object
            TemplateCompiledTransform = CreateCompiledTransform(TemplateDom);
        }

        public static DocumentTemplate GetTemplate(string templatePath)
        {
            if (AllowCache && HttpContext.Current != null && HttpContext.Current.Cache != null)
            {
                if (HttpContext.Current.Cache[templatePath] != null)
                {
                    DocumentTemplate cached = (DocumentTemplate)HttpContext.Current.Cache[templatePath];

                    return cached;
                }
            }

            DocumentTemplate template = new DocumentTemplate(templatePath);

            // saves object into cache
            if (AllowCache)
            {
                HttpContext.Current.Cache.Insert(templatePath, template, new System.Web.Caching.CacheDependency(template.DependenciesPaths.ToArray()));
            }

            return template;
        }
    }
}
